package com.pluszg.nutrition.order.service.impl;

import com.pluszg.nutrition.api.rpc.account.AccountApi;
import com.pluszg.nutrition.api.rpc.product.ProductApi;
import com.pluszg.nutrition.database.mapper.order.OrderMapper;
import com.pluszg.nutrition.common.exception.PlusBusinessException;
import com.pluszg.nutrition.model.order.Order;
import com.pluszg.nutrition.model.product.Product;
import com.pluszg.nutrition.order.service.OrderService;
import com.pluszg.nutrition.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductApi productApi;

    @Autowired
    private AccountApi accountApi;

    @Override
    public Order submit (Order order) {
        this.saveOrder(order);
        Product product = productApi.findById("359664607e6a43f989789c3d44d75dbb").getResult();
        log.info("商品信息{}",product.toString());
        return order;
    }

    @Override
    public Order findById (String id){
        return orderMapper.loadById(id).orElseThrow(()-> new PlusBusinessException("未找到对应订单"));
    }

    public void createOrder (Order order) {
        this.saveOrder(order);
        productApi.deduct(order.getProductCode(),order.getCount());
        accountApi.reduceAccount(order.getAccountCode(),order.getAmount());
    }

    public Order saveOrder(Order order) {
        if (StringUtils.isBlank(order.getId())) {
            order.setId(RandomUtil.generateUUID());
            orderMapper.insert(order);
            return order;
        } else {
            orderMapper.update(order);
            return order;
        }
    }
}
